package com.modules.contentImages.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.common.response.ResponseVO;
import com.common.utils.R;
import com.modules.contentImages.entity.ContentImages;
import com.modules.contentImages.service.IContentImagesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/content_images")
public class ContentImagesController {

    @Autowired
    private IContentImagesService contentImagesService;
    @Value("${yiyun.file.upload-path}")
    String uploadPath;
    @Value("${yiyun.file.domain-path}")
    String domainPath;

    // 分组的分页列表
    @RequestMapping("/getPageList")
    public R getPageList(@RequestParam Map<String, Object> params){
        return contentImagesService.getPageList(params);
    }

    // 图片列表
    @GetMapping("/getList")
    public R getList(){
        return R.ok().put("data", contentImagesService.list());
    }

    // 获得单个图片信息
    @GetMapping ("/getEntityById/{id}")
    public R getEntityById(@PathVariable Integer id){
        ContentImages contentImages = contentImagesService.getOne(new QueryWrapper<ContentImages>().lambda().eq(ContentImages::getId, id));
        return R.ok().put("data", contentImages);
    }

    // 添加图片
    @PostMapping("/saveEntity")
    public R saveEntity(@RequestBody ContentImages contentImages, MultipartFile file){

        if (contentImages.getId() == null){
            contentImages.setCreateTime(new Date());
        }

        contentImagesService.saveOrUpdate(contentImages);
        return R.ok();
    }

    // 删除图片
    @DeleteMapping("/removeEntity/{id}")
    public R removeEntity(@PathVariable Integer id){
        ContentImages contentImages = this.contentImagesService.getById(id);
        contentImagesService.removeById(contentImages);
        return R.ok();
    }

    // 上传图片
    @PostMapping("/upload")
    public R upload( MultipartFile file) throws IOException {
        String newFileName = SecureUtil.md5(String.valueOf(DateUtil.current()));
        String extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") - 1);
        String toPath = uploadPath +newFileName+ extName;
        String filePath = domainPath +newFileName+ extName;
        file.transferTo(new File(toPath));
        return R.ok().put("data", filePath);
    }
}
